//
//  AddressViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/20.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "AddressViewController.h"
#import "ConfigDefine.h"
#import "MallRequestManager.h"
#import "AddressModel.h"
#import "AllAddressViewController.h"
@interface AddressViewController ()<UITextFieldDelegate>


@end

@implementation AddressViewController
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField ==self.phoneTextField) {
        self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        
    }
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self showNavgationWithLeftItemWithTitle:@""];
    self.title = @"填写收货地址";
    //姓名框
    self.nameTextField.layer.borderColor = RGB(209, 209, 209).CGColor;
    self.nameTextField.placeholder = @"收货人姓名";
    self.nameTextField.layer.borderWidth = 1;
    self.nameTextField.delegate = self;
    //手机号码框
    self.phoneTextField.layer.borderColor = RGB(209, 209, 209).CGColor;
    self.phoneTextField.placeholder = @"手机号码";
    self.phoneTextField.layer.borderWidth = 1;
    self.phoneTextField.delegate = self;
    //地址框
    self.areaView.layer.borderColor = RGB(209, 209, 209).CGColor;
    self.areaView.layer.borderWidth = 1;
    self.addressLabel.textColor = [UIColor darkGrayColor];
    self.addressLabel.text = @"";
    self.detailText.textAlignment = NSTextAlignmentRight;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.areaView addGestureRecognizer:tap];

    //详细地址框
    self.detailAddressTextView.layer.borderColor = RGB(209, 209, 209).CGColor;
    self.detailAddressTextView.placeholder=@"详细地址";
    [self.detailAddressTextView setPlaceholderFont:[UIFont systemFontOfSize:17]];
    self.detailAddressTextView.layer.borderWidth = 1;
    [self.detailAddressTextView addMaxTextLengthWithMaxLength:50 andEvent:^(BRPlaceholderTextView *text) {
        [self.detailAddressTextView endEditing:YES];
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超过指定长度" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
    }];
    //保存按钮
    self.saveBtn.layer.cornerRadius = 25.0;
    [self.saveBtn setBackgroundColor:RGB(0, 172, 230)];
    if ([self.userInfo.allKeys containsObject:@"address"]) {
        AddressModel *model = [self.userInfo objectForKey:@"address"];
        self.nameTextField.text = model.name;
        self.phoneTextField.text  =model.tel;
        self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@",model.province,model.city,model.district];
        self.detailAddressTextView.text  =model.address;
    }
}
- (void)tap:(UITapGestureRecognizer *)tap
{
    [self.view addSubview:self.addressView];
    [self.nameTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
    [self.detailAddressTextView resignFirstResponder];
    self.addressView = [[AddressView alloc] init:^(NSString *address ,NSString *addressId) {
    self.addressLabel.text = address;
        self.addressArr = [NSArray new];
        self.addressArr = [addressId componentsSeparatedByString:@"|"];
    }];
    self.addressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
}
-(void)saveBtnClicked:(UIButton *)sender
{
    if ([self.nameTextField.text isEqualToString:@""]) {
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"姓名不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        return;
    }
    else if ([self.phoneTextField.text isEqualToString:@""]) {
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        return;
    }
    else if (![self isMobile:self.phoneTextField.text])
    {
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式不正确" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        return;
    }
    else if ([self.addressLabel.text isEqualToString:@""]) {
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"所在地区不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        return;
    }
    else if ([self.detailAddressTextView.text isEqualToString:@""]) {
        UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"详细地址不能为空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        return;
    }
    else
    {
        NSMutableDictionary *params = [NSMutableDictionary new];
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
        
        [params setObject:userId forKey:@"user_id"];
        [params setObject:token forKey:@"token"];
        NSString *name = self.nameTextField.text;
        NSString *tel = self.phoneTextField.text;
        NSString *province = [self.addressArr objectAtIndex:0];
        NSString *city = [self.addressArr objectAtIndex:1];
        NSString *district = [self.addressArr lastObject];
        
        self.addressView = [[AddressView alloc] init:^(NSString *address ,NSString *addressId) {
            self.addressLabel.text = address;
            self.addressArr = [NSArray new];
            self.addressArr = [addressId componentsSeparatedByString:@"|"];
        }];
        if (province==nil) {
            if ([self.userInfo.allKeys containsObject:@"address"]) {
                AddressModel *model = [self.userInfo objectForKey:@"address"];
                NSString *location = model.location;
                NSArray *locationArr = [location componentsSeparatedByString:@"|"];
                NSLog(@"locationArr:%@",locationArr);
                [params setObject:[locationArr firstObject] forKey:@"province"];
                [params setObject:[locationArr objectAtIndex:1] forKey:@"city"];
                [params setObject:[locationArr lastObject] forKey:@"district"];
            }
        }
        else
        {
            [params setObject:province forKey:@"province"];
            [params setObject:city forKey:@"city"];
            [params setObject:district forKey:@"district"];
        }
        NSString *detailAddress = self.detailAddressTextView.text;
        [params setObject:name forKey:@"name"];
        [params setObject:tel forKey:@"tel"];
        [params setObject:detailAddress forKey:@"address"];
        
        if (_flag ==1) {
           AddressModel *model =  [self.userInfo objectForKey:@"address"];

            [params setObject:model.uid forKey:@"address_id"];

        }else
        {
            [params setObject:@"0" forKey:@"address_id"];
            
        }
       
        [MallRequestManager post:Updatereceivingaddress RequestParams:params  FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) {
                NSLog(@"connectionError:%@",connectionError);
            }
            else
            {
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                [self performSelectorOnMainThread:@selector(popToVC) withObject:nil waitUntilDone:YES];
            }
        }];
    }
}
- (void)popToVC
{
    [self.navigationController popViewControllerAnimated:YES];
     [[NSNotificationCenter defaultCenter]postNotificationName:newAddress object:nil];
}
-(void)backTo
{
    [self.navigationController popViewControllerAnimated:NO];
    if (self.flag == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:popFromAddressVC object:nil];
    }
}

/**
 *  手机号码验证
 *
 *  @param mobileNumbel 传入的手机号码
 *
 *  @return 格式正确返回true  错误 返回fals
 */
- (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}
@end
